<?php
//检查传参
$mac_id = isset($_GET['mac_id']) ? trim($_GET['mac_id']) : '';
$app_id = isset($_GET['app_id']) ? intval($_GET['app_id']) : 0;
$channel_id = isset($_GET['channel_id']) ? trim($_GET['channel_id']) : '';
if (empty($mac_id) || empty($app_id) || empty($channel_id)) {
    die(json_encode(array(
        'error' => 50001,
        'message' => 'empty mac_id, app_id or channel_id',
    )));
}

if (strpos(PHP_OS, 'WIN') === false) {
    mysql_connect('10.77.0.102', 'izhushou', 'HJGTYUFTYDRT9866HGFG');
} else {
    mysql_connect('10.1.20.42', 'izhushou', 'HJGTYUFTYDRT9866HGFG');
}
mysql_select_db('izhushou');
mysql_set_charset("utf8");

//查询mac地址记录
$sql = "select * from spread_demo
        where app_id = '$app_id'
        and mac_id = '$mac_id'
        order by add_time desc
        limit 1";
$query = mysql_query($sql);
$row = mysql_fetch_assoc($query);

//mac地址不存在
if (empty($row['mac_id'])) {
    die(json_encode(array(
        'error' => 0,
        'message' => 'success',
        'is_valid' => 0,
        'active_time' => '',
        'fail_reason' => 'mac地址不存在',
    )));
}

//查到记录，如果已经验证过直接返回结果
if ($row['status'] != 0) {
    $is_valid = $row['status'] == 1 ? 1 : 0;
    die(json_encode(array(
        'error' => 0,
        'message' => 'success',
        'is_valid' => $is_valid,
        'active_time' => $row['add_time'],
        'fail_reason' => $row['fail_reason'],
    )));
}

//查到记录，如果未验证，先验证mac地址是否有效，改库并返回结果
$is_valid = 0;
$fail_reason = '';
if (strtotime($row['add_time']) < time() - 86400 * 7) {
    $is_valid = 0;
    $fail_reason = '过期未验证';
} else {
    $is_valid = 1;
    $fail_reason = '';
}

$status = $is_valid == 1 ? 1 : 10000;
$sql = "update spread_demo set
        status = $status,
        fail_reason = '$fail_reason',
        channel_id = '$channel_id'
        where id = {$row['id']}";
$query = mysql_query($sql);

die(json_encode(array(
    'error' => 0,
    'message' => 'success',
    'is_valid' => $is_valid,
    'active_time' => $row['add_time'],
    'fail_reason' => $fail_reason,
)));
?>